﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Runtime.CompilerServices;
using System.Web;
using System.Web.Compilation;
using System.Web.UI;
using System.Web.WebPages;

namespace DotNetNuke.Web.DDRMenu
{
	public class Razor
	{
		public void Execute(
			string virtualPath,
			HtmlTextWriter htmlWriter,
			object source,
			string controlID,
			string clientOptions,
			string dnnPath,
			string manifestPath,
			string portalPath,
			string skinPath,
			Dictionary<string, string> templateArguments)
		{
			var webPage = GetWebPage(virtualPath);

			dynamic model = new ExpandoObject();
			model.Source = source;
			model.ControlID = controlID;
			model.Options = clientOptions;
			model.DNNPath = dnnPath;
			model.ManifestPath = manifestPath;
			model.PortalPath = portalPath;
			model.SkinPath = skinPath;

			foreach (var arg in templateArguments)
			{
				model[arg.Key] = arg.Value;
			}

			webPage.ExecutePageHierarchy(
				new WebPageContext(new HttpContextWrapper(HttpContext.Current), webPage, model), htmlWriter, webPage);
		}

		public WebPageBase GetWebPage(string virtualPath)
		{
			var compiledType = BuildManager.GetCompiledType(virtualPath);
			return RuntimeHelpers.GetObjectValue(Activator.CreateInstance(compiledType)) as WebPageBase;
		}
	}
}